package com.liu.queue.storage;

import com.liu.message.impl.ResponseMessage;
import com.liu.queue.message.MessageTypeEnum;
import com.liu.queue.message.PullMessage;
import com.liu.queue.message.PushMessage;
import com.liu.queue.message.StoragePushMessage;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @param
 * @BelongsProject: QueueDemo2
 * @BelongsPackage: com.liu.queue.store
 * @author: L
 * @Date: 2023/10/20 10:34
 * @return
 */

public class StorageProvider {
    private static volatile StorageProvider storageProvider;
    private static final List<Storage> storages =new CopyOnWriteArrayList<>();

    private StorageProvider() {
        registerStorage(null);
    }
    public static boolean registerStorage(String path){
        return storages.add(StorageFind.getStorage(path));
    }

    public static ResponseMessage handlerPush(PushMessage pushMessage) {
        StorageProvider instance = getInstance();
        Storage storage = instance.getStorage(pushMessage.getMessageType());
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setMessageID(pushMessage.getMessageID());
        try {
            storage.cache(pushMessage);
            storage.persistence(pushMessage);
        }catch (Exception e){
            responseMessage.setExceptionValue(e);
            return responseMessage;
        }
        responseMessage.setReturnValue("successful");
        return responseMessage;
    }

    public static ResponseMessage HandlerPull(PullMessage message){
        StorageProvider instance = getInstance();
        Storage storage = instance.getStorage(message.getMessageType());
        List<StoragePushMessage> pushMessages = storage.get(message.getTopic(), message.getNum());
        ResponseMessage responseMessage = new ResponseMessage();
        if (pushMessages==null || pushMessages.isEmpty()){
            return responseMessage;
        }
        // List<String> bodys=new ArrayList<>();
        // pushMessages.forEach(m->{
        //     try {
        //         String body = new String(m.getBody(), "UTF-8");
        //         bodys.add(body);
        //     } catch (UnsupportedEncodingException e) {
        //         throw new RuntimeException(e);
        //     }
        // });
        responseMessage.setReturnValue(pushMessages);
        return responseMessage;
    }

    private Storage getStorage(MessageTypeEnum messageType){
        for (Storage storage: storages){
            if (storage.support(messageType)){
                return storage;
            }
        }
        throw new RuntimeException("找不到对应类型的解析器,消息类型: " + messageType);
    }


    private static StorageProvider getInstance() {
        if (storageProvider ==null){
            synchronized (StorageProvider.class){
                if (storageProvider ==null){
                    storageProvider =new StorageProvider();
                }
            }
        }
        return storageProvider;
    }
}
